﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using OnlineVideos.Data;
using Common.Library;
using System.Xml;
using System.IO;
using System.ServiceModel.Syndication;
using Microsoft.Phone.Tasks;
using System.Text;
using TweetSharp;
using OnlineVideos.Entities;
using System.Threading.Tasks;
using System.Collections.ObjectModel;
using Newtonsoft.Json.Linq;
using Common.Utilities;

namespace Social_Celebrities
{  
    public partial class Feeds : PhoneApplicationPage
    {    
        public IDictionary<string, ObservableCollection<commentsclass>> commentsDic1 = default(Dictionary<string, ObservableCollection<commentsclass>>);
        TwitterLoginPage p = new TwitterLoginPage();
        string PersonID = string.Empty;
        public Feeds()
        {
            InitializeComponent();
            Loaded += Feeds_Loaded;
        }
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            if (NavigationContext.QueryString.TryGetValue("PersonId",out PersonID))
            {
            }
        }
        private void LoadAds()
        {
            try
            {
                PageHelper.LoadAdControl(LayoutRoot, FeedStackAd, 1);
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in LoadAds Method In MainPage.xaml file file", ex);
                string excepmess = "Exception in LoadAds Method In MainPage.xaml file.\n\n" + ex.Message + "\n\n StackTrace :- \n" + ex.StackTrace;
            }
        }
        void Feeds_Loaded(object sender, RoutedEventArgs e)
        {
            LoadAds();
            try
            {
                int id = Convert.ToInt32(PersonID);
                Title.Text = Task.Run(async () => await Constants.connection.Table<CastProfile>().Where(i => i.PersonID == id).FirstOrDefaultAsync()).Result.Name;
                foreach (Phone_SocialFeed sf in Task.Run(async () => await Constants.connection.Table<Phone_SocialFeed>().Where(i => i.PersonId == id).ToListAsync()).Result)
                {
                    PerformanceProgressBar pb = (PerformanceProgressBar)this.FindName(sf.FeedType.ToLower() + "Progressbar");
                    pb.IsIndeterminate = true;
                    if (sf.FeedType.ToLower() == "facebook")
                    {
                        if (!string.IsNullOrEmpty(sf.FeedLink))
                        {
                            LoadFeeds(sf.FeedLink, sf.FeedType);
                        }
                    }
                    else if (sf.FeedType.ToLower() == "twitter")
                    {
                        if (!string.IsNullOrEmpty(sf.FeedLink))
                        {
                            if (sf.FeedLink.Contains("=") && sf.FeedType == "Twitter") //&& sf.FeedType=="Twitter"
                            {
                                LoadFromTwitter(sf.FeedLink.Substring(sf.FeedLink.IndexOf("=") + 1), sf.FeedType);
                            }
                            else
                            {
                                LoadFromTwitter(sf.FeedLink, sf.FeedType);
                            }
                        }
                    }
                    else
                    {
                        if (!string.IsNullOrEmpty(sf.FeedLink))
                        {
                            LoadFeeds(sf.FeedLink, sf.FeedType);
                        }
                    }
                }
                AppSettings.BackgroundAgenError = "Feeds_Loaded Method in Feeds.xaml.cs completed Successfully..!!";
            }
            catch (Exception ex)
            {
                //Exceptions.SendErrortoMail("Exception at Feeds_Loaded Method in Feeds.xaml.cs Page and the error is " + " " + ex.Message + " " + ex.StackTrace);
                Exceptions.SaveOrSendExceptions("Exception at Feeds_Loaded Method in Feeds.xaml.cs Page", ex);
                AppSettings.BackgroundAgenError = ex.Message;
            }
        }
        private void LoadFromTwitter(string CelebrityLink,string feedtype)
        {
            try
            {
                var service = new TwitterService("LYTy3T8P556GxqRymimhwA", "5TSKipEjESOAcdBsViWm2E1RVxFEN1Ooh0nRwIj7RsY");
                if (p.getAccessToken() != null)
                {
                    string[] Tokens = new string[2];
                    Tokens = p.ReturnTokens(p.getAccessToken());
                    if (Tokens[0] != null)
                    {
                        service.AuthenticateWith(Tokens[0], Tokens[1]);
                        service.ListTweetsOnUserTimeline(new ListTweetsOnUserTimelineOptions() { ScreenName = CelebrityLink }, (ts, rep) =>
                        {
                            if (rep.StatusCode == HttpStatusCode.OK)
                            {
                                Deployment.Current.Dispatcher.BeginInvoke(() =>
                                {
                                    lbxtwitter.ItemsSource = ts;
                                    TextBlock tb = (TextBlock)this.FindName(feedtype.ToLower() + "ErrorMessage");
                                    tb.Visibility = Visibility.Collapsed;
                                    PerformanceProgressBar pb = (PerformanceProgressBar)this.FindName(feedtype.ToLower() + "Progressbar");
                                    pb.IsIndeterminate = false;
                                });
                            }
                            else
                            {
                                Deployment.Current.Dispatcher.BeginInvoke(() =>
                               {
                                   TextBlock tb = (TextBlock)this.FindName(feedtype.ToLower() + "ErrorMessage");
                                   tb.Visibility = Visibility.Visible;
                                   PerformanceProgressBar pb = (PerformanceProgressBar)this.FindName(feedtype.ToLower() + "Progressbar");
                                   pb.IsIndeterminate = false;
                               });
                            }
                        });
                    }
                }
                else
                {
                    TextBlock tb = (TextBlock)this.FindName(feedtype.ToLower() + "ErrorMessage");
                    tb.Visibility = Visibility.Visible;
                    PerformanceProgressBar pb = (PerformanceProgressBar)this.FindName(feedtype.ToLower() + "Progressbar");
                    pb.IsIndeterminate = false;
                }
            }
            catch(Exception ex)
            {
                //Exceptions.SendErrortoMail("Exception at LoadFromTwitter Method in Feeds.xaml.cs Page and the error is " + " " + ex.Message + " " + ex.StackTrace);
                Exceptions.SaveOrSendExceptions("Exception at LoadFromTwitter Method in Feeds.xaml.cs Page", ex);
            }
        }
        private void LoadFeeds(string feedurl,string feedtype)
        {
            commentsDic1 = new Dictionary<string, ObservableCollection<commentsclass>>();
            WebClient wclient = new WebClient();
            try
            {
                if (feedtype.ToLower() == "blog" && feedurl.EndsWith("blogspot.com/") || feedurl.EndsWith("blogspot.in/"))
                {
                    feedurl = feedurl + "feeds/posts/default?alt=rss";
                }
                else if (feedtype.ToLower() == "blog" && feedurl.EndsWith("tumblr.com/") || feedurl.EndsWith("tumblr.in/"))
                {
                    feedurl = feedurl + "rss";
                }
                else if (feedtype.ToLower() == "blog" && feedurl.EndsWith("wordpress.com/") || feedurl.EndsWith("wordpress.in/"))
                {
                    feedurl = feedurl + "feed";
                }
                wclient.OpenReadCompleted += (sender1, e1) =>
                {
                    if (e1.Error != null)
                    {
                        TextBlock tb = (TextBlock)this.FindName(feedtype.ToLower() + "ErrorMessage");
                        tb.Visibility = Visibility.Visible;
                        Deployment.Current.Dispatcher.BeginInvoke(() =>
                        {
                            PerformanceProgressBar pb = (PerformanceProgressBar)this.FindName(feedtype.ToLower() + "Progressbar");
                            pb.IsIndeterminate = false;
                        });
                        return;
                    }
                    else
                    {
                         Deployment.Current.Dispatcher.BeginInvoke(() =>
                        {
                        TextBlock tb = (TextBlock)this.FindName(feedtype.ToLower() + "ErrorMessage");
                        tb.Visibility = Visibility.Collapsed;
                        });
                    }
                    Stream str = e1.Result;
                    str.Position = 0;
                    string ReturnValue = string.Empty;
                    using (var reader = new StreamReader(str, Encoding.UTF8))
                    {
                        ReturnValue = reader.ReadToEnd();
                    }
                        ReturnValue = ReturnValue.Replace("+00:00", "").Replace(" <access:restriction relationship=\"deny\" xmlns:access=\"http://www.bloglines.com/about/specs/fac-1.0\" />", "");
                        bool Check = UpdateFeedList(ReturnValue, feedtype);
                        str.Close();
                        if (Check == false)
                        {
                            TextBlock tb = (TextBlock)this.FindName(feedtype.ToLower() + "ErrorMessage");
                            tb.Visibility = Visibility.Visible;
                        }
                        else
                        {
                            TextBlock tb = (TextBlock)this.FindName(feedtype.ToLower() + "ErrorMessage");
                            tb.Visibility = Visibility.Collapsed;
                        }
                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        PerformanceProgressBar pb = (PerformanceProgressBar)this.FindName(feedtype.ToLower() + "Progressbar");
                        pb.IsIndeterminate = false;
                    });
                };
                wclient.OpenReadAsync(new Uri(feedurl, UriKind.RelativeOrAbsolute));
                AppSettings.BackgroundAgenError = "LoadFeeds Method in Feeds.xaml.cs page Completed Successfully.!!!";
            }
            catch (Exception ex)
            {
                //Exceptions.SendErrortoMail("Exception at LoadFeeds Method in Feeds.xaml.cs Page and the error is " + " " + ex.Message + " " + ex.StackTrace);               
                Exceptions.SaveOrSendExceptions("Exception at LoadFeeds method in Feeds.xaml.cs page",ex);
                AppSettings.BackgroundAgenError = ex.Message;
            }
        }
       
        private bool UpdateFeedList(string feedXML,string Feedtype)
        {
            StringReader stringReader = new StringReader(feedXML);
            XmlReaderSettings settings = new XmlReaderSettings();
            settings.DtdProcessing = DtdProcessing.Parse;
            settings.XmlResolver = null;
            XmlReader xmlReader = XmlReader.Create(stringReader,settings);           
            try
            {
                SyndicationFeed feed = SyndicationFeed.Load(xmlReader);
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                  int PersonID= Convert.ToInt32(AppSettings.PersonID);
                  Phone_SocialFeed DataRow = Task.Run(async () => await Constants.connection.Table<Phone_SocialFeed>().Where(i => i.PersonId == PersonID && i.FeedType == Feedtype).FirstOrDefaultAsync()).Result;
                   if (DataRow != null)
                   {
                       DataRow.LastAccessed = feed.Items.OrderByDescending(i => i.PublishDate).FirstOrDefault().PublishDate.DateTime;
                       DataRow.UpdatesAvailable = Convert.ToBoolean(0);
                       Constants.connection.UpdateAsync(DataRow);
                   }
                    if (Feedtype.ToLower() == "facebook")
                    {
                        lbxfacebook.ItemsSource = feed.Items;
                    }
                    else
                    {
                        lbxblog.ItemsSource = feed.Items;
                    }
                });
                AppSettings.BackgroundAgenError = "UpdateFeedList Method in Feeds.xaml.cs page Completed Successfully..!!!";
                return true;
            }                
            catch(Exception ex)
            {
                //Exceptions.SendErrortoMail("Exception at UpdateFeedList Method in Feeds.xaml.cs Page and the error is " + " " + ex.Message + " " + ex.StackTrace);
                Exceptions.SaveOrSendExceptions("Exception at UpdateFeedList Method in Feeds.xaml.cs page",ex);
                AppSettings.BackgroundAgenError = ex.Message;
                return false;
            }
        }
        void face_GetCompleted(object sender, Facebook.FacebookApiEventArgs e)
        {
            try
            {
                ObservableCollection<commentsclass> commentsList = new ObservableCollection<commentsclass>();
                JObject o1 = JObject.Parse(e.GetResultData().ToString());
                JArray a = (JArray)o1["data"];
                foreach (var o in a)
                {
                    commentsclass cc = new commentsclass();
                    cc.Name = (string)o["from"]["name"];
                    cc.Comment = (string)o["message"];
                    string date = (string)o["created_time"];
                    date = date.Split(' ')[0].ToString();
                    //DateTime dt = Convert.ToDateTime(date);
                    DateTime dt = DateTime.Parse(date);
                    cc.Date = dt;
                    commentsList.Add(cc);
                }
                commentsDic1.Add(((SyndicationItem)e.UserState).Id, commentsList);
                Constants.SelectedSyndicationItem[0] = ((SyndicationItem)e.UserState);
                Constants.SelectedSyndicationItem[1] = commentsDic1.Where(i => i.Key == ((SyndicationItem)e.UserState).Id).FirstOrDefault().Value;
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    NavigationService.Navigate(new Uri("/Views/feedPage.xaml?FeedType=FaceBook", UriKind.Relative));
                });
                AppSettings.BackgroundAgenError = "face_GetCompleted Method in Feeds.xaml.cs Completed Successfully..!!!";
            }
            catch (Exception ex)
            {
                //Exceptions.SendErrortoMail("Exception at face_GetCompleted Method in Feeds.xaml.cs Page and the error is " + " " + ex.Message + " " + ex.StackTrace);
                Exceptions.SaveOrSendExceptions("Exception at face_GetCompleted Method in Feeds.xaml.cs page", ex);
                AppSettings.BackgroundAgenError = ex.Message;
            }
        }       

        private void lbxfacebook_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (lbxfacebook.SelectedIndex == -1)
                return;
            if (string.IsNullOrEmpty(AppSettings.FaceBookAccessToken))
            {
                NavigationService.Navigate(new Uri("/Views/FacebookLoginPage.xaml", UriKind.Relative));
                lbxfacebook.SelectedIndex = -1;
            }
            else
            {
                SyndicationItem item = (SyndicationItem)lbxfacebook.SelectedItem;
                string PostId = string.Empty;
                Facebook.FacebookClient face = new Facebook.FacebookClient(AppSettings.FaceBookAccessToken);
                string Link = item.Links.FirstOrDefault().Uri.ToString();
                if (Link.Contains("fbid="))
                {
                    PostId = Link.Substring(Link.IndexOf('=') + 1, ((Link.IndexOf('&') - 1) - Link.IndexOf('=')));
                }
                else if (Link.Contains("?type=1") || Link.Contains("&type=1"))
                {
                    string lin = Link.Replace("/?type=1", "").Replace("?set=", "").Replace("&type=1", "");
                    PostId = lin.Substring(lin.LastIndexOf('/') + 1);
                }
                else if (Link.Contains("video.php?v="))
                {
                    PostId = Link.Substring(Link.LastIndexOf("?v=") + 3);
                }
                else
                {
                    PostId = Link.Substring(Link.LastIndexOf('/') + 1);
                }
                face.GetAsync("/" + PostId + "/comments", new Dictionary<string, object> { { "fields", "id,message,from,created_time" } }, item);
                face.GetCompleted += face_GetCompleted;

                lbxfacebook.SelectedIndex = -1;
            }
        }

        private void lbxtwitter_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (lbxtwitter.SelectedIndex == -1)
                return;
            if (p.getAccessToken() == null)
            {
                NavigationService.Navigate(new Uri("/Views/TwitterLoginPage.xaml", UriKind.Relative));
                lbxtwitter.SelectedIndex = -1;
            }
            else
            {
                Constants.SelectedSyndicationItem[0] = (TwitterStatus)lbxtwitter.SelectedItem;
                NavigationService.Navigate(new Uri("/Views/feedPage.xaml?FeedType=Twitter", UriKind.Relative));
                lbxtwitter.SelectedIndex = -1;
            }
        }

        private void lbxblog_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (lbxblog.SelectedIndex == -1)
                return;
            if (string.IsNullOrEmpty(AppSettings.BloggerAccessToken))
            {
                NavigationService.Navigate(new Uri("/Views/BloggerLogin.xaml", UriKind.Relative));
                lbxblog.SelectedIndex = -1;
            }
            else
            {
                Constants.SelectedSyndicationItem[0] = (SyndicationItem)lbxblog.SelectedItem;
                NavigationService.Navigate(new Uri("/Views/feedPage.xaml?FeedType=Blog", UriKind.Relative));
                lbxblog.SelectedIndex = -1;
            }
        }       

        private void Reldbtn_Click(object sender, EventArgs e)
        {
            Feeds_Loaded(null,null);
        }

        private void btnshare_Click(object sender, EventArgs e)
        {
            UploadToBlog upload = new UploadToBlog(Convert.ToInt32(AppSettings.PersonID), this);
        }       
    }
}